package com.tg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tg.mapper.UserMapper;
import com.tg.pojo.User;
import com.tg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean register(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(null != user.getUsername(), User::getUsername, user.getUsername());
        User user1 = userMapper.selectOne(lambdaQueryWrapper);
        if (user1 == null) {
            String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(password);
            int insert = userMapper.insert(user);
            return insert >= 1 ? true : false;
        } else return false;
    }

    public User login(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        lambdaQueryWrapper.eq(null != user.getUsername(), User::getUsername, user.getUsername())
                .eq(null != user.getPassword(),User::getPassword, user.getPassword());
        User user1 = userMapper.selectOne(lambdaQueryWrapper);
        return user1;
    }

    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        return user;
    }

    @Override
    public User getFriendByUsername(String addFriendUsername) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUsername,addFriendUsername);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        return user;
    }

    @Override
    public List<User> getUsers(String[] usernames) {
        if (usernames == null) {
            return null;
        }
        return userMapper.getUsers(usernames);
    }
}
